//
//  SQRechargeViewController.m
//  pai
//
//  Created by pro on 14-11-5.
//  Copyright (c) 2014年 linjunjing. All rights reserved.
//

#import "SQRechargeViewController.h"
#import "Global.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "DataSigner.h"

@interface SQRechargeViewController ()

@end

@implementation SQRechargeViewController
@synthesize scrollView = _scrollView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"充值"];
    
    [self initview];
}

-(void)initview
{
    _scrollView = [[UIScrollView alloc]init];
    [_scrollView setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    _scrollView.frame = CGRectMake(0, self.MyNavigationBar.frame.origin.y+self.MyNavigationBar.frame.size.height, 320, [[UIScreen  mainScreen] bounds].size.height - 44 - self.MyNavigationBar.frame.origin.y-self.MyNavigationBar.frame.size.height);
    _scrollView.pagingEnabled = NO;
    _scrollView.delegate = self;
    _scrollView.bounces = YES;
    [self.view addSubview:_scrollView];
    
    SQRechargeCell *rechage = [SQRechargeCell initmyview];
    [rechage initPayType];
    rechage.delegate = self;
    [_scrollView addSubview:rechage];
    
    _scrollView.contentSize = CGSizeMake(320, rechage.frame.size.height);
}

-(void)dorecharge:(NSString *)price withType:(NSString *)type
{
    NSLog(@"%@",price);
    NSLog(@"%@",type);
    
    float money = [price floatValue];
    price = [NSString stringWithFormat:@"%f",money*100];
    
    self.payType = type;
    self.money = money;
    
    biz_inpour_t inpour;
    inpour.base.msgtype = 8014;
    inpour.base.len = sizeof(inpour);
    inpour.base.error = 0;
    if ([type isEqualToString:@"alipay"]) {
        inpour.channel = 10;
    }else if([type isEqualToString:@"wechat"]) {
        inpour.channel = 11;
    }
    strcpy(inpour.userid, [[Global instance].userinfo.username UTF8String]);
    strcpy(inpour.amt, [price UTF8String]);
    if ([Global instance].devicetoken) {
        strcpy(inpour.devicetoken, [[Global instance].devicetoken UTF8String]);
    }
    else{
        strcpy(inpour.devicetoken, "");
    }
    
    NSMutableData* msgData = [NSMutableData data];
    [msgData appendBytes:&inpour length:sizeof(inpour)];
    
    [super sendData:msgData tag:1 withHUD:YES];

}
//读取数据
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    biz_inpour_ack_t inpourack;
    [data getBytes:&inpourack length:sizeof(inpourack)];
    NSLog(@"data len:%lu",data.length);
    NSLog(@"%d",inpourack.base.error);
    NSLog(@"%d",inpourack.base.len);
    if(inpourack.base.error==ACS_SUCCESS){
        //获取成功，跳转到支付界面
        if ([self.payType isEqualToString:@"alipay"]) {
            [self alipay:inpourack];
        }else if([self.payType isEqualToString:@"wechat"]) {
            [self wechat:inpourack];
        }
        [self.HUD showAnimated:YES whileExecutingBlock:^{
            [self.HUD show:NO];
        } completionBlock:^{
        }];
    }else if(inpourack.base.error==3060){
        //出错
        [self.HUD showAnimated:YES whileExecutingBlock:^{
            self.HUD.labelText = @"充值金额有误";
            sleep(2);
            [self.HUD show:NO];
        } completionBlock:^{
        }];
        return;
    }else if(inpourack.base.error==3062){
        //出错
        [self.HUD showAnimated:YES whileExecutingBlock:^{
            self.HUD.labelText = @"充值出错";
            sleep(2);
            [self.HUD show:NO];
        } completionBlock:^{
        }];
        return;
    }
}
-(void)alipay:(biz_inpour_ack_t)inpour
{
    NSString *notifyURL =[NSString stringWithUTF8String:inpour.notifyURL];
    NSLog(@"url：%@",notifyURL);
    NSString *partner = @"2088611102975103";
    NSString *seller = @"tongping@soqik.net";
    NSString *privateKey = @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANm9QTP9kf61fWCC76bvas+If953KYu7dnjqjpt+zlmbHBrPCQd/klY812BlDDy+xmdVdpQhAW8Lv6ZkXQ3Sy6UxD/5VcH1qNrItx+zQvJS3DEC/TH8wtp2GXFUtEmr42oxE56Mb9o4Rt4RoXi6iNM/tZQKQVU+HVVZPPMiW1XKnAgMBAAECgYBf3F95eTiub868D8lcsGlQ5yKMmd/Tofu9rl6MfN5yOsS71Mx/3Z1alDyqNrKVh9QnqEulWYadEgoVQnhpXpXC21sLHoRlpNFzlEhUDPoWUd1jNEjjr+NJpERmeanfYdWm7hhTKbtgw0M8VJUON51QPC3hSCzWak/Cm2etQpxEIQJBAPgZiKWTGS5PDpWOxAa9KI8UktIyHXWTkxgMxcshyNsOsCm02C+YaoUlKs+QLPvQxj4D85ufzAfApzM2Dzd0cXECQQDgrDpHu1rfHWBp+LA3lN6IYRyGi1atgkPnBYecEeVmTXafx2EQdN2wk5iDiun2kUD07hw81UEjn7+zH5sR+pmXAkEA3aJh0hhQnG//hVeegq6k9vzYFHK0on6NHyT55Xdu6VJ7ySZHIm20avFDB12y8doV3vzEuTfNmvdd5n/apB2f4QJAXR3EgdpazUIFpaYWktK2cFufUPwLDpqAvg0CqWKZaw8L7SjbR9DH2NkzSsGWOkT1YQ4W0feoqbUZ5Ili4c61PQJAXou1enYaHu9hw5Agz+wnrFKgJqC4PtUQVRpxY4GWjIsGhmIm6ntPQQTuTIYISCT+q/XJzn5zzGiOtXiPXqS09A==";
    NSString *serialnum = [NSString stringWithUTF8String:inpour.serialnum];
    
    /*
	 *生成订单信息及签名
	 */
	//将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
	order.partner = partner;
	order.seller = seller;
	order.tradeNO = serialnum; //订单ID（由商家自行制定）
	order.productName = @"杭州速擎科技有限公司"; //商品标题
	order.productDescription = @"竞拍系统充值"; //商品描述
	//order.amount = [NSString stringWithFormat:@"%.2f",0.01]; //商品价格
    order.amount = [NSString stringWithFormat:@"%.2f",self.money];
	order.notifyURL =  notifyURL; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
	
	//应用注册scheme,在AlixPayDemo-Info.plist定义URL types
	NSString *appScheme = @"pai";
	
	//将商品信息拼接成字符串
	NSString *orderSpec = [order description];
	NSLog(@"orderSpec = %@",orderSpec);
	
	//获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
	id<DataSigner> signer = CreateRSADataSigner(privateKey);
	NSString *signedString = [signer signString:orderSpec];
    
	//将签名成功字符串格式化为订单字符串,请严格按照该格式
	NSString *orderString = nil;
	if (signedString != nil) {
		orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        NSLog(@"orderSpec = %@",orderString);
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            
            NSLog(@"reslut = %@",resultDic);
            NSString* msg = @"";
            if ([[resultDic objectForKey:@"resultStatus"]integerValue]==9000) {
                msg = @"支付成功";
            }else if ([[resultDic objectForKey:@"resultStatus"]integerValue]==8000)
            {
                msg = @"正在处理";
            }else if ([[resultDic objectForKey:@"resultStatus"]integerValue]==4000)
            {
                msg = @"订单支付失败";
            }else if ([[resultDic objectForKey:@"resultStatus"]integerValue]==6001)
            {
                msg = @"用户中途取消";
            }else if ([[resultDic objectForKey:@"resultStatus"]integerValue]==6002)
            {
                msg = @"网络连接出错";
            }else
            {
                msg = @"订单支付失败";
            }
            UIAlertView* alterView = [[UIAlertView alloc]initWithTitle:nil message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alterView show];
        }];
    }
}
-(void)wechat:(biz_inpour_ack_t)inpour
{
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
